<template>
  <section>
    <transition enter-active-class="animate__animated animate__fadeIn" mode="out-in">
      <section>
        <!-- 查询表单 -->
        <ZyTableQueryForm
          v-model:ruleForm="query.params"
          :rules="queryRule"
          @query="goPage(1)"
          @reset="goReset"
        >
          <el-form-item style="margin-right: 200px;">
            <el-button type="primary" style="width: 68px; height: 24px;" @click="openAddDialog">新增</el-button>
          </el-form-item>
        </ZyTableQueryForm>

        <!-- 新增弹窗 -->
        <el-dialog title="新增 RTSP 流" v-model="adddialogVisible" width="500px">
          <el-form :model="addform" ref="addFormRef" label-width="100px" :rules="addRules">
            <el-form-item label="RTSP 流地址" prop="rtspUrl">
              <el-input v-model="addform.rtspUrl" placeholder="请输入 RTSP 流地址" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="adddialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddForm">提交</el-button>
          </template>
        </el-dialog>

        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          @sort-change="handleSortChange"
          @selection-change="handleSelectionChange"
          row-key="app"
          :expand-row-keys="expandedRowKeys"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="url" label="拉流地址" align="center" width="100" show-overflow-tooltip />
          <el-table-column prop="key" label="键" align="center" width="100" show-overflow-tooltip />

          <el-table-column prop="api" label="转流播放协议地址" align="center" width="1000">
            <template #default="{ row }">
              <el-table
                :data="[row.api || {}]"
                border
                size="small"
                style="width: 100%; font-size: 12px;"
                header-row-class-name="hidden-header"
              >
                <el-table-column label="flv" prop="flv" align="center" />
                <el-table-column label="mp4" prop="mp4" align="center" />
                <el-table-column label="rtmp" prop="rtmp" align="center" />
                <el-table-column label="rtsp" prop="rtsp" align="center" />
                <el-table-column label="ts" prop="ts" align="center" />
              </el-table>
            </template>
          </el-table-column>

          <el-table-column prop="src" label="源信息" align="center" width="300">
            <template #default="{ row }">
              <el-table
                :data="[row.src || {}]"
                border
                size="small"
                style="width: 100%; font-size: 12px;"
                header-row-class-name="hidden-header"
              >
                <el-table-column label="应用名称" prop="app" align="center" />
                <el-table-column label="流名称" prop="stream" align="center" />
                <el-table-column label="虚拟主机名" prop="vhost" align="center" />
              </el-table>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="流状态" width="150" align="center">
            <template #default="{ row }">
              <el-button :type="row.status === 0 ? 'success' : 'danger'" size="small" round plain>
                {{ row.status === 0 ? '正常' : '异常' }}
              </el-button>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150">
            <template #default="{ row }">
              <el-button type="primary" @click="handlePlay(row.api.mp4)">播放</el-button>
              <el-button type="danger" @click="openDelDialog(row.key)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- ✅ 修复分页事件 -->
        <ZyElPagination
          v-model:currentPage="query.pagination.current"
          v-model:pageSize="query.pagination.pageSize"
          :total="tempData.total"
          @current-change="goPage"
          @size-change="handleSizeChange"
        />

        <!-- 删除弹窗 -->
        <el-dialog v-model="dialogVisible" title="确认删除" width="400px">
          <el-form :model="form" ref="delFormRef">
            <el-form-item label="Key">
              <el-input v-model="form.key" disabled />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="danger" @click="submitDelForm">确认删除</el-button>
          </template>
        </el-dialog>

        <!-- 播放弹窗 -->
        <el-dialog
          v-model="playDialogVisible"
          width="60%"
          :before-close="handleClosePlayDialog"
          center
          title="视频预览"
          class="custom-video-dialog"
        >
          <div class="video-wrapper">
            <video
              ref="videoRef"
              :src="currentPlayUrl"
              controls
              autoplay
              class="custom-video-player"
            ></video>
          </div>
          <template #footer>
            <el-button type="primary" @click="handleClosePlayDialog">关闭</el-button>
          </template>
        </el-dialog>
      </section>
    </transition>
  </section>
</template>

<script>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api/axios.js'
import { API_ZLK_HTTP, API_ZLK_RTMP, API_ZLK_RTSP } from '@/config.js'

export default {
  name: 'YourComponentName',

  data() {
    return {
      playDialogVisible: false,
      currentPlayUrl: '',
      query: reactive({
        params: { app: '' },
        pagination: { current: 1, pageSize: 10 }
      }),
      queryRule: reactive({}),
      tempData: reactive({ total: 0 }),
      dialogVisible: false,
      form: reactive({ key: '' }),
      adddialogVisible: false,
      addform: reactive({ rtspUrl: '' }),
      expandedRowKeys: [],
      tableData: []  // ✅ 普通数组
    }
  },

  methods: {
    handlePlay(url) {
      this.currentPlayUrl = url
      this.playDialogVisible = true
    },

    handleClosePlayDialog() {
      this.playDialogVisible = false
      this.currentPlayUrl = ''
      const video = this.$refs.videoRef
      if (video && !video.paused) video.pause()
    },

    openDelDialog(key) {
      this.form.key = key
      this.dialogVisible = true
    },

    async submitDelForm() {
      try {
        await api.post('/delStreamProxy', new URLSearchParams({ key: this.form.key }))
        ElMessage.success('删除成功')
        this.dialogVisible = false
        this.getData()
      } catch (err) {
        ElMessage.error('删除失败')
      }
    },

    openAddDialog() {
      this.addform.rtspUrl = ''
      this.adddialogVisible = true
    },

    submitAddForm() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        try {
          const res = await api.post('/addStreamProxy', new URLSearchParams({ url: this.addform.rtspUrl }))
          if (res.code !== 400) {
            ElMessage.success('新增成功!')
            this.adddialogVisible = false
            this.getData()
          } else {
            ElMessage.error("新增失败！")
          }
        } catch (err) {
          ElMessage.error('新增失败')
        }
      })
    },

    async getData() {
      try {
        const res = await api.post('/listStreamProxy')
        const data = res.data || []

        const enhanced = data.map(item => {
          const app = item.src.app || ''
          const stream = item.src.stream || ''
          return {
            ...item,
            api: {
              mp4: `${API_ZLK_HTTP}${app}/${stream}.live.mp4`,
              rtmp: `${API_ZLK_RTMP}${app}/${stream}`,
              rtsp: `${API_ZLK_RTSP}${app}/${stream}`,
              ts: `${API_ZLK_HTTP}${app}/${stream}.live.ts`,
              flv: `${API_ZLK_HTTP}${app}/${stream}.live.flv`
            }
          }
        })

        const { current, pageSize } = this.query.pagination
        const filtered = enhanced.filter(item => !this.query.params.app || item.app?.includes(this.query.params.app))
        this.tempData.total = filtered.length
        this.tableData = filtered.slice((current - 1) * pageSize, current * pageSize)
        this.expandedRowKeys = []
      } catch (err) {
        this.tableData = []
        this.tempData.total = 0
        this.expandedRowKeys = []
      }
    },

    goPage(page) {
      this.query.pagination.current = page
      this.getData()
    },

    handleSizeChange(size) {
      this.query.pagination.pageSize = size
      this.query.pagination.current = 1
      this.getData()
    },

    goReset() {
      this.query.params.app = ''
      this.query.pagination.current = 1
      this.getData()
    },

    handleSortChange(e) {
      console.log('排序变化', e)
    },

    handleSelectionChange(selection) {
      console.log('选中项', selection)
    }
  },

  mounted() {
    this.getData()
  }
}
</script>

<style scoped>
.custom-video-dialog .el-dialog__header {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  background-color: #1f1f1f;
  color: #fff;
  border-bottom: 1px solid #333;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.custom-video-dialog .el-dialog {
  background-color: #2b2b2b;
  color: #ffffff;
  border-radius: 12px;
}

.video-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #000;
  padding: 12px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}

.custom-video-player {
  width: 100%;
  max-height: 70vh;
  border-radius: 8px;
  background-color: #000;
}
</style>